package com.gaojinqi.base.common.util;

import com.google.common.base.Joiner;
import org.springframework.util.StringUtils;

import java.util.Collection;

/**
 * @author gao.jinqi
 * @date 2020-03-21 00:50
 */
public class StringUtil {

    public static String asString(Object obj) {
        return asString(obj, "");
    }

    public static String asString(Object obj, String defaultValue) {
        return obj == null ? defaultValue : obj.toString();
    }

    /**
     * 将字符串转换为Integer类型，若转换失败，则赋值0
     */
    public static int asInteger(Object obj) {
        return asInteger(obj, 0);
    }

    /**
     * 将字符串转化为Integer类型
     *
     * @param defaultValue 若转换失败，则赋值defaultValue
     */
    public static int asInteger(Object obj, int defaultValue) {
        if (obj == null) {
            return defaultValue;
        }
        try {
            return Integer.decode(obj.toString().trim());
        } catch (NullPointerException nullpointerexception) {
            return defaultValue;
        } catch (NumberFormatException numberformatexception) {
            return defaultValue;
        }
    }

    /**
     * 将集合以指定分隔符拼接字符串
     * [1,2,3] + "|"  === > 1|2|3
     */
    public static String joinSplitter(Iterable<?> iterable, String splitter) {
        return Joiner.on(splitter).skipNulls().join(iterable);
    }

    /**
     * 将数组以指定分隔符拼接字符串
     * [1,2,3] + "|"  === > 1|2|3
     */
    public static String joinSplitter(Object[] arr, String splitter) {
        return Joiner.on(splitter).skipNulls().join(arr);
    }

}
